package com.sjzs.web.tset.base;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import junit.framework.Assert;

@SuppressWarnings("rawtypes")
public class DomainTestCase extends Assert {
	protected static Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
	static {
		map.put(int.class, 1);
		map.put(Integer.class, 1);
		map.put(long.class, 1L);
		map.put(Long.class, 1L);
		map.put(boolean.class, true);
		map.put(Boolean.class, true);
		map.put(Date.class, new Date(1000000));
		map.put(List.class, new ArrayList());
		map.put(String[].class, new String[] {});
		map.put(BigDecimal.class, new BigDecimal("1"));
		map.put(byte[].class, new byte[] {});
	}

	protected void processDomain(Object obj) {
		Class<?> clz = obj.getClass();
		Method[] methods = clz.getDeclaredMethods();
		for (Method m : methods) {
			String methodName = m.getName();
			if (methodName.startsWith("set") || methodName.startsWith("get") || methodName.startsWith("is") || methodName.equals("toString")) {
				callMethod(obj, clz, m);
			}
		}
	}

	protected Object[] callMethod(Object obj, Class<?> clz, Method m) {
		Object[] parameters = null;
		Class<?>[] parameterTypes = m.getParameterTypes();
		if (parameterTypes != null && parameterTypes.length > 0) {
			parameters = new Object[parameterTypes.length];
			for (int i = 0; i < parameters.length; i++) {
				boolean good = initMethodParams(parameterTypes, parameters, i);
				if (!good) {
					return null;
				}
			}
		}
		try {
			m.invoke(obj, parameters);
		} catch (Exception e) {
			fail("调用对象[" + clz.getSimpleName() + "]方法[" + m.getName() + "]的时候出错！" + e.getMessage());
		}
		return parameters;
	}

	private boolean initMethodParams(Class<?>[] parameterTypes, Object[] parameters, int i) {
		Class<?> c = parameterTypes[i];
		try {
			initProtype(parameters, i, c);
			return true;
		} catch (Exception e) {
			fail("初始化对象[" + c.getSimpleName() + "]的时候出错！" + e.getMessage());
		}
		return false;
	}

	private void initProtype(Object[] parameters, int i, Class<?> c) throws InstantiationException, IllegalAccessException {

		Set<Class<?>> keySet = map.keySet();
		for (Iterator<Class<?>> iter = keySet.iterator(); iter.hasNext();) {
			Class<?> clzz = iter.next();
			if (c.isAssignableFrom(clzz)) {
				parameters[i] = map.get(clzz);
			}
		}
		if (null == parameters[i]) {
			parameters[i] = c.newInstance();
		}
	}
}
